<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
			<span>
				<i class="el-icon-open"></i>
				业务流程授权
			</span>
		</div>
    <div class="text item">
      <el-form :inline="true" :model="AdvancedQuery" class="demo-form-inline" style="float: left;height:43px" @submit.native.prevent>
          <!-- 左侧搜索按钮 -->
          <el-form-item label="">
            <el-input clearable v-model="textSearch" placeholder="请输入系统/业务编码" style="width:240px;"
            @keyup.enter.native="getProcessList" @clear="getProcessList">
            <el-button slot="append" icon="el-icon-search" @click="getProcessList"></el-button>
          </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="advancedQuery">
              高级查询
              <i class="el-icon-magic-stick"></i>
            </el-button>
          </el-form-item>
          <!-- 右侧操作按钮 -->
          <el-form-item style="float:right">
            <el-button @click="handleadd" type="primary" plain>
                新增
                <i class="el-icon-plus"></i>
            </el-button>
          </el-form-item>
        </el-form>
      <!-- 表格 -->
      <div class="el-flex el-box-column">
        <el-table :data="tableData" ref="tableData"  height="100%" style="width: 100%" border stripe>
          <el-table-column show-overflow-tooltip sortable min-width="100" align="center" prop="number" label="序号"  type="index"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="150"  prop="domainName" label="系统"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="180" align="center" prop="orgName" label="机构"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="160" prop="processName" label="流程"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="147" prop="businessCode" label="业务编码"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="200" prop="businessUrl" label="业务填报页面"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="100" prop="businessDesc" label="业务描述"></el-table-column>
          <el-table-column show-overflow-tooltip prop="control" align="center" label="操作" width="110" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" icon="el-icon-edit" title="编辑" @click="handleEdit(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" type="text" icon="el-icon-delete" title="删除" @click="handDelete(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
         <!-- 分页表格 -->
        <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
      </div>
      <!-- 新增或修改编辑弹框 -->
        <el-dialog :title="modalTitle" :visible.sync="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleAddClose"  class="elAdded">
          <div class="container">
            <el-form label-width="100px" ref="editData" :model="editData" :rules="ruleValidate">
              <el-form-item label="系统" prop="domainName">
                <el-col :span="18">
                  <el-select v-model="editData.domainId" :disabled="isOk" placeholder="请选择"  @change="domainChange">
                      <el-option
                      v-for="item in optionDatas"
                      :key="item.value"
                      :label="item.domainName"
                      :value="item.domainId">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
              <el-form-item label="机构" prop="orgName">
                <el-col :span="18">
                  <el-input 
                  readonly 
                  placeholder="请输入机构" 
                  v-model="editData.orgName"
                  v-show="!isOk"
                  >
                  <i v-show="editData.orgName" slot="suffix" class="el-input__icon el-icon-circle-close" @click="clearParentName" style="cursor: pointer;"></i>
                    <el-button @click="openMechanism" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                  <el-input 
                  readonly 
                  placeholder="请输入机构" 
                  v-model="editData.orgName"
                  v-show="isOk"
                  >
                  
                  </el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="流程" prop="processName">
                <el-col :span="18">
                  <el-input 
                  readonly 
                  placeholder="请输入流程" 
                  v-model="editData.processName"
                  >
                  <i v-show="editData.processName" slot="suffix" class="el-input__icon el-icon-circle-close" @click="clearParentName1" style="cursor: pointer;"></i>
                    <el-button @click="pOrgShowEvt" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="业务编码" prop="businessCode">
                <el-col :span="18">
                   <el-input placeholder="请输入业务编码" :disabled="isOk"  v-model="editData.businessCode" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="业务填报页面" prop="businessUrl">
                <el-col :span="18">
                   <el-input placeholder="请输入业务填报页面"  v-model="editData.businessUrl" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="页面描述" prop="businessDesc">
                <el-col :span="18">
                   <el-input placeholder="请输入页面描述" type="textarea" :rows="2"  v-model="editData.businessDesc" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>

            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="handleCheck">保存<i class="el-icon-document-checked el-icon--right"></i></el-button>
              <el-button type="danger" @click="handleCloseCheck(false)">关闭 <i class="el-icon-close"></i></el-button>
          </span>
        </el-dialog>
        <!-- 高级查询弹窗 -->
        <el-drawer
          title="高级查询"
          :visible.sync="dialogVisibleSearch" 
          :before-close="searchClose"
          direction="rtl"
          custom-class="demo-drawer"
          ref="drawer"
          :wrapperClosable="true"
          :close-on-press-escape="false"
        >
          <div class="demo-drawer__content el-box-column" style="height: 100%; margin-right:10px;">
                <el-form label-width="90px" ref="formAdvancedQuery" :model="formAdvancedQuery" class="el-flex">
                  <el-form-item label="系统" prop="domainName">
                    <el-col :span="24">
                      <el-select v-model="formAdvancedQuery.domainName" placeholder="请选择系统">
                        <el-option
                          v-for="item in optionDatas"
                          :key="item.value"
                          :label="item.domainName"
                          :value="item.domainName">
                        </el-option>
                      </el-select>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="业务编码" prop="businessCode" >
                      <el-col :span="18">
                        <el-input  placeholder="请根据业务编码或名称查询" v-model="formAdvancedQuery.businessCode" clearable></el-input>
                    </el-col>
                  </el-form-item>
                </el-form>
                <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
                    <el-button type="primary" @click="getProcessList">确定<i class="el-icon-document-checked el-icon--right"></i></el-button>
                    <el-button @click="handleSearchClose">重置
                      <i class="el-icon-refresh-left"></i>
                    </el-button>
                </div>
              </div>
        </el-drawer>
         <!-- 机构选项抽屉式弹框 -->
         <el-drawer
            title="选择隶属机构"
            :visible.sync="affiliates" 
            :before-close="organ"
            direction="rtl"
            custom-class="demo-drawer"
            ref="drawer"
            :wrapperClosable="true"
            :close-on-press-escape="false"
          >
            <div class="demo-drawer__content el-box-column" style="height: 100%; margin-right:10px;">
              <el-scrollbar style="height: 100%;overflow-x: hidden">
                  <el-tree
                  ref="pOrgTree"
                  @check-change="orgTreeChange"
                  :props="orgTreeProps"
                   node-key="orgId" 
                   lazy 
                   :key="treeKey"
                   show-checkbox 
                  :load="loadProcessTree"
                  :check-strictly="true" 
                  :check-on-click-node="true"
                  style="height:100%"
                  >
                </el-tree>
                </el-scrollbar>
                  <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
                      <el-button type="primary" @click="pOrgSureEvt">确定<i class="el-icon-document-checked el-icon--right"></i></el-button>
                      <el-button @click="affiliates = false">取消
                        <i class="el-icon-refresh-left"></i>
                      </el-button>
                  </div>
                </div>
          </el-drawer>
           <!-- 流程选项抽屉式弹框 -->
          <el-drawer
            title="选择流程"
            :visible.sync="processDrawer" 
            :before-close="processClosure"
            direction="rtl"
            custom-class="demo-drawer"
            ref="drawer"
            :wrapperClosable="true"
            :close-on-press-escape="false"
          >
            <div class="demo-drawer__content el-box-column" style="height: 100%; margin-right:10px;">
              <el-scrollbar style="height: 100%;overflow-x: hidden">
                  <el-tree
                    show-checkbox
                    node-key="id"
                    ref="procTree"
                    lazy
                    :key="treeKey"
                    :load="loadNodeGetProcessTree"
                    :check-strictly="true"
                    :check-on-click-node="true"
                    @check-change="processChange"
                    :props="propsProcessTree"
                    style="height:100%">
                  </el-tree>
                </el-scrollbar>
                  <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
                      <el-button type="primary" @click="processDetermine">确定<i class="el-icon-document-checked el-icon--right"></i></el-button>
                      <el-button @click="processDrawer = false">取消
                        <i class="el-icon-refresh-left"></i>
                      </el-button>
                  </div>
                </div>
          </el-drawer>
    </div>
  </el-card>
</template>

<script>
import {Tree, Dialog, Table, TableColumn, Pagination, MessageBox, Message, Drawer, Scrollbar} from "element-ui"
import { getDomainAuth, organizationRoot, organizationParent } from '@/api/authority/userAuthorization/userAuthorization.js'
import { 
  workflowProcessBusiness,
  workflowGetProcessTree,
  workflowGetProcessCatalog,
  workflowGetProcessProcess,
  workflowProcessBusinessDelete,
  workflowProcessBusinessAdd,
  workflowProcessBusinessEdit,
  workflowProcessBusinessDetails
} from '@/api/workflow/processAuthority/processAuthority.js'
  export default {
    components: {
    'el-tree': Tree, //树形菜单
    "el-table": Table, //表格
    "el-table-column": TableColumn, //表格列
    "el-pagination": Pagination, //分页
    "el-dialog": Dialog, //对话框
    "el-pagination": Pagination, //分页
    "el-drawer": Drawer, //抽屉
    "el-scrollbar": Scrollbar
  },
    data() {
      var dataList ={
        domainId:"",
        domainName:'',
        orgName:'',
        orgId:'',
        processName:'',
        processId:'',
        processCode: '',
        businessCode:'',
        businessUrl:'',
        businessDesc:''
      }
      return {
        textSearch:'', //模糊查询框
        dialogVisible:false, //新增或修改弹框
        modalTitle: '', // 新增或修改title
        AdvancedQuery:{},
        formAdvancedQuery: {}, // 高级查询form对象
        AdvancedQuery:JSON.parse(JSON.stringify(dataList)), 
        affiliates:false, //抽屉式隶属机构
        editData:JSON.parse(JSON.stringify(dataList)),
        dataList: JSON.parse(JSON.stringify(dataList)),
        processSearch: '', //流程选择搜索控制
        pOrgSearchDatas: [], //隶属机构数据源
        dialogVisibleSearch:false, //高级查询
        processDrawer:false, //流程查询抽屉弹框
        pageSize: 20, //每页展示条数
        currentPage: 1, //默认显示页数
        total:0, //总条数
        treeKey: 1, // 自动刷新树
        isOk:false,
        optionDatas:[],
         propsProcessTree: {
          label: 'name',
          isLeaf: 'isLeaf',
          disabled: this.disabledFn
        },
        count: 1,
        orgTreeProps: { //机构树
          label: 'orgName',
          isLeaf: 'isLeaf',
        },
        tableData:[], //获取业务流程授权列表
        ruleValidate:{
           domainName: [{
            required: true,

            message: "系统不能为空",

            trigger: "blur"
          }],
           processName: [{
            required: true,

            message: "流程不能为空",

            trigger: "blur"
          }],
          businessCode: [{
            required: true,

            message: "业务编码不能为空",

            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getProcessList()
      // this.getSystemList()
    },
    methods: {
      domainChange(value){
        this.optionDatas.forEach((v,i)=>{
          if(v.domainId == value){
            this.editData.domainName = v.domainName
          }
        })
      },
      //获取业务流程授权列表
      getProcessList(){
        var data = {}
        if (this.dialogVisibleSearch) { //高级查询
          data.type = 2;
          Object.assign(data, this.formAdvancedQuery);
        } else { //模糊查询 
          data.type = 1;
          data.expression = this.textSearch;
        }
        workflowProcessBusiness(this.currentPage, this.pageSize, data).then(res =>{
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.dialogVisibleSearch = false;
          setTimeout(() => {
              this.$refs.tableData.doLayout(); //表格刷新以后，重绘表格宽度
          }, 0)
        })
      },
      // 高级查询重置按钮事件
      handleSearchClose () {
        this.$refs.formAdvancedQuery.resetFields()
        this.dialogVisibleSearch = false
        this.getProcessList()
      },
       // 每页条数
      handleSizeChange(val) {
        this.pageSize = val
        this.getProcessList()
      },
      // 当前页数
      handleCurrentChange(val) {
        this.currentPage = val
        this.getProcessList()
      },
      //获取系统数据
      getSystemList(){
        getDomainAuth().then(res =>{
          this.optionDatas = res.data.data
        })
      },
      //获取隶属机构树形结构数据
      loadProcessTree(node, resolve){
        if (node.level == 0) {
          let $this = this;
          organizationRoot().then(res => {
            let orgDatas = res.data.data;
            orgDatas.forEach(e => {
              if (e.isLeaf == 'n') {
                e.isLeaf = false;
              } else {
                e.isLeaf = true;
              }
            });
            resolve(orgDatas);
          });
        } else {
          let id = node.data.orgId;
          organizationParent(id)
            .then(res => {
              let orgDatas = res.data.data.records;
              orgDatas.forEach(e => {
                if (e.isLeaf == 'n') {
                  e.isLeaf = false;
                } else {
                  e.isLeaf = true;
                }
              });
              resolve(orgDatas);
            })
            .catch(res => {
              resolve([]);
            });
        }
      },
      //disabled函数
    disabledFn (data, node) {
      if (data.type == "CATALOG" || data.type == "ACTIVITY") {  
        return true
      } else {
        return false
      }
    },
      // 获取添加流程树形结构数据
    loadNodeGetProcessTree (node, resolve) {
      if (node.level === 0) {
        workflowGetProcessTree().then(res => {
          if (res.data.code === 10000) {
            let processCatalogTreeData = res.data.data.processTree
            resolve(processCatalogTreeData)
          }
        }).catch(res => {
          resolve([])
        })
      } else {
        if (node.data.type == 'CATALOG') { // 目录
          let parentCatalogId = node.data.id
          workflowGetProcessCatalog(parentCatalogId).then(res => {
            if (res.data.code === 10000) {
              let catalogTreeData = res.data.data.processTree
               catalogTreeData.forEach(e => {
              if (e.type == 'PROCESS') {
                e.isLeaf = true;
              } else {
                e.isLeaf = false;
              }
            });
              resolve(catalogTreeData)
            }
          }).catch(res => {
            resolve([])
          })
        } else if (node.data.type == 'PROCESS') { // 流程
          let processId = node.data.id
          workflowGetProcessProcess(processId).then(res => {
            if (res.data.code === 10000) {
              let processData = res.data.data.processTree
              resolve(processData)
            }
          }).catch(res => {
            resolve([])
          })
        } else {
          return resolve([])
        }
      }
    },
      //流程点击跳出弹框
      pOrgShowEvt(){
        this.processDrawer = true
      },
      // 选择组织弹窗，确定事件
      pOrgSureEvt() {
        let cData = this.$refs.pOrgTree.getCurrentNode();
        if (!cData) {
          //如果未选中节点，则视为清空操作
          cData = {
            label: '',
            orgId: ''
          };
        }
          this.editData.orgName = cData.orgName; //赋显示值
          this.editData.orgId = cData.orgId; //赋真实值
        
        this.organ() //关闭弹窗
      },
      //流程确定按钮
      processDetermine(){
        let cData = this.$refs.procTree.getCurrentNode();// 获取选中的行数据
        if (!cData) {
          //如果未选中节点，则视为清空操作
          cData = {
            label: '',
            orgId: ''
          };
        }
          this.editData.processName = cData.name; //赋显示值
          this.editData.processId = cData.id; //赋真实值
          this.editData.processCode = cData.code
         this.processDrawer = false
         this.treeKey += 1
      },
      //流程弹框关闭按钮
      processClosure(){
        this.treeKey += 1
        this.processDrawer = false
      },
      //机构树点击事件
      orgTreeChange(data, checked, indeterminate){
        if (checked) {
          this.$refs.pOrgTree.setCheckedKeys([data.orgId]);
          this.$refs.pOrgTree.setCurrentKey(data.orgId);
        }
      },
      //流程树点击事件
      processChange(data, checked, indeterminate){
        if (checked) {
          this.$refs.procTree.setCheckedKeys([data.id]);
          this.$refs.procTree.setCurrentKey(data.id);
        }
      },
      //高级查询点击按钮
      advancedQuery(){
        this.getSystemList()
        this.dialogVisibleSearch = true
        this.AdvancedQuery = JSON.parse(JSON.stringify(this.dataList))
        this.AdvancedQuery.domainName = ''
        this.AdvancedQuery.businessCode = ''
      },
      //新增按钮
      handleadd(){
        this.dialogVisible = true
        this.modalTitle = '新增业务与流程授权信息'
        this.isOk = false
        this.editData = JSON.parse(JSON.stringify(this.dataList))
        this.getSystemList()
      },
      //编辑按钮
      handleEdit(index,row){
        this.dialogVisible = true
        this.modalTitle = '编辑业务与流程授权信息'
        this.isOk = true
        // this.editData = JSON.parse(JSON.stringify(row));
        workflowProcessBusinessDetails(row.mapId).then(res => {
          console.log(res)
          this.editData = res.data.data
        })
      },
      //保存按钮
      handleCheck(row){
        this.$refs.editData.validate(valid => {
          if (valid) {
            this.dialogVisible = false
            let params = {
              "businessCode":this.editData.businessCode,
              "businessUrl":this.editData.businessUrl,
              "businessDesc":this.editData.businessDesc,
              "createdByName": this.editData.createdByName,
              "domainId": this.editData.domainId,
              "domainName": this.editData.domainName,
              "orgId": this.editData.orgId,
              "orgName":this.editData.orgName,
              "processCode":this.editData.processCode,
              "processId": this.editData.processId,
              "processName":this.editData.processName,
              "mapId":this.editData.mapId
            }
            if (this.modalTitle == '新增业务与流程授权信息') {
              workflowProcessBusinessAdd(params).then(res =>{
                this.getProcessList()
                Message.success("保存成功")
              }).catch(error =>{
                Message.error("保存失败")
              })
            } else if (this.modalTitle == '编辑业务与流程授权信息') {
              workflowProcessBusinessEdit(params).then(res =>{
                this.getProcessList()
                Message.success("保存成功")
              }).catch(error =>{
                Message.error("保存失败")
              })
            }
          }
        })
      },
      // 删除按钮
      handDelete(index,row){
         MessageBox.confirm('您是否确定删除选中内容', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            workflowProcessBusinessDelete(row.mapId).then(res =>{
              if(res.data.code = 10000){
                this.getProcessList()
                Message.success("删除成功")
              }
            }).catch(error =>{
             Message.info('删除失败')  
          })
        }).catch(() => {
          Message.info('已取消删除')       
        });

      },
      //关闭弹框 × 按钮
      handleAddClose(){
        this.dialogVisible = false
      },
      //关闭弹框关闭按钮
      handleCloseCheck(){
        this.handleAddClose()
        this.$refs.editData.resetFields(); //重置校验
      },
      //隶属机构抽屉关闭按钮
      organ(){
        this.affiliates = false
        this.treeKey += 1
      },
      
      //打开机构树抽屉式弹框
      openMechanism(){
        this.affiliates = true
      },
      //高级查询抽屉关闭按钮
      searchClose(){
        this.dialogVisibleSearch = false
      },
      //高级查询确定按钮
      querySure(){
        this.dialogVisibleSearch = false
      },
      
      clearParentName(){
        this.editData.orgName = ''
      },
      clearParentName1(){
        this.editData.processName = ''
      },
    }
  };
</script>
